package com.ankicoo.database.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.ankicoo.database.constant.DataSourceConst.DATA_SOURCE_CENTER;
import static com.ankicoo.database.constant.DataSourceConst.DATA_SOURCE_DEFAULT;

@Component
@Primary
public class DynamicDatasource  extends AbstractRoutingDataSource {
    // 数据源标识，为了保证线程安全使用threadLocal
    public static ThreadLocal<String> name = new ThreadLocal<>();

    @Autowired
    private DataSource dataSource;
    @Autowired
    private DataSource dataSource2;

    /**
     * 此方法作用是返回当前数据源标识
     * @return 数据源标识
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return name.get();
    }

    /** 重写父类方法之前，为父类基础属性进行赋值 */
    @Override
    public void afterPropertiesSet() {
        // targetDataSources初始化所有数据源
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DATA_SOURCE_DEFAULT, dataSource);
        targetDataSources.put(DATA_SOURCE_CENTER, dataSource2);
        super.setTargetDataSources(targetDataSources);
        // defaultTargetDataSource设置默认数据源
        super.setDefaultTargetDataSource(dataSource);
        super.afterPropertiesSet();
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (DATA_SOURCE_CENTER.equals(name.get())){
            return dataSource2.getConnection();
        }else {
            return dataSource.getConnection();
        }
    }
}
